var http = require('http');
var qs = require('querystring');

//get方式获取内容
exports.get = function(host, port, path, data, callback) {
    var content = qs.stringify(data);
    var opt = {
        method: 'GET',
        host: host,
        port: port,
        path: path + '?' + content,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    http.get(opt, function(res) {
        if(res.statusCode === 200) {
            res.on('data', function(body) {
                callback(0, body);
            });
        } else {
            callback(res.statusCode);
        }
    }).on('error',function(e) {
        callback(-1, 'Got error: ' + e.message);
    });
};

//post方式获取内容
exports.post = function(host, port, path, data, callback) {
    var content = qs.stringify(data);
    var opt = {
        method: 'POST',
        host: host,
        port: port,
        path: path,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    var req = http.request(opt, function(res) {
        if(res.statusCode === 200) {
            res.on('data', function(body) {
                callback(0, body);
            });
        } else {
            callback(res.statusCode);
        }
    }).on('error',function(e) {
        callback(-1, 'Got error: ' + e.message);
    });
    req.write(content);
    req.end();
};

var data = {
    name: '123'
};

exports.get('127.0.0.1', 8088, '/admin/test.jsp', data, function(code, body) {
    console.log('code:'+code+'|\tbody:'+body);
});

exports.post('127.0.0.1', 8088, '/admin/test.jsp', data, function(code, body) {
    console.log('code:'+code+'|\tbody:'+body);
});